﻿using System;
using System.Threading.Tasks;
using Moven.Data;
using Moven.Helpers;
using Xamarin.Forms;
using static Moven.Statics;

namespace Moven.Views
{
	public partial class SyncPage
	{
		FileImageSource _closeImage = "delete.png", _closeDisabledImage = "delete_disabled.png";

		Command _goBackCommand;

		bool _isBookmarkSyncTest = false;

		public SyncPage()
		{
			InitializeComponent();
			BindingContext = this;

			AbsoluteLayout.SetLayoutBounds(titleBar, new Rectangle(0, 0, 1, IsAndroid ? 50 : 60));
			var phoneNo = Settings.PhoneNo;
			if (!phoneNo.IsNullOrEmpty())
			{
				phoneNoEntry.Text = phoneNo;
			}

			_goBackCommand = new Command(GoBack, () => !IsBusy);
			titleLabel.Effects.Add(Effect.Resolve("Moven.LightFontLabelEffect"));
			closeImageButton.Source = _closeImage;
			tapGestureRecognizer.Command = _goBackCommand;

			UpdateSyncButton();
			UpdatePhoneNoHintLabel();
			phoneNoEntry.TextChanged += delegate
			{
				UpdateSyncButton();
				UpdatePhoneNoHintLabel();
			};
			syncButton.Clicked += async delegate {
				IsBusy = true;

				ShowHUD("正在同步收藏, 请稍候...");

				UpdateUI();

				SyncBookmarksData result = null;
				if (_isBookmarkSyncTest)
				{
					await Task.Delay(TimeSpan.FromSeconds(5));
					result = new SyncBookmarksData { Status = SyncBookmarksStatus.Success };
				}
				else
				{
					result = await Statics.ArticlesStore.SyncBookmarksAsync(phoneNoEntry.Text);
				}
				var status = result.Status;
				if (!IsVisible || !IsCurrentPage)
				{
					return;
				}
				Device.BeginInvokeOnMainThread(() =>
				{
					IsBusy = false;
					UpdateUI();

					var success = status != SyncBookmarksStatus.Failure;
					var message = success ? "同步成功, 请退出本页面" : "同步失败, 请检查网络连接, 稍后再试";
					if (success)
					{
						ShowSuccessHUDWithStatus(message);
					}
					else
					{
						ShowErrorHUDWithStatus(message);
					}
				});
			};
		}

		void GoBack()
		{
			if (IsBusy || !IsVisible)
			{
				return;
			}
			Navigation.PopModalAsync();
		}

		void UpdateSyncButton()
		{
			syncButton.IsEnabled = phoneNoEntry.Text.IsValidMainlandMobilePhoneNo();
			if (syncButton.IsEnabled)
			{
				Settings.PhoneNo = phoneNoEntry.Text;
			}
		}

		void UpdatePhoneNoHintLabel()
		{
			phoneNoHintLabel.Text = phoneNoEntry.Text.IsNullOrEmpty() ? string.Empty : "免验证手机号";
		}

		void UpdateUI()
		{
			syncButton.IsEnabled = phoneNoEntry.IsEnabled = !IsBusy;
			closeImageButton.Source = IsBusy? _closeDisabledImage : _closeImage;
			_goBackCommand.ChangeCanExecute();
		}

		protected override void OnAppearing()
		{
			UpdateUI();

			base.OnAppearing();

			if (phoneNoEntry.Text.IsNullOrEmpty())
			{
				phoneNoEntry.Focus();
			}
		}

		protected override void OnDisappearing()
		{
			base.OnDisappearing();

			IsBusy = false;
		}
	}
}
